from .flow import get_flow
from .utils.parse_input import parse_input


def chat(user_input, conversation_history=None):
    """
    Handle chat (free conversation) with the agent.
    
    Args:
        user_input (str): The user's input message
        conversation_history (list, optional): Previous conversation history
        
    Returns:
        tuple: (result, shared) where:
            - result (str): The agent's response
            - shared (dict): The complete shared context dictionary
    """
    # Initialize conversation history if not provided
    if conversation_history is None:
        conversation_history = []
    
    # Initialize shared store for this conversation turn
    shared = {
        "input_type": "chat",
        "user_input": None,
        "conversation_history": conversation_history,
        "response": None
    }
    
    try:
        # Parse input for chat mode
        parsed_input = parse_input(user_input, "chat")
        shared["user_input"] = parsed_input
        
        # Get the appropriate flow for chat mode and run it
        flow = get_flow("chat")
        flow.run(shared)
        
        # Get the result
        result = shared["response"]
        
        return result, shared
        
    except Exception as e:
        error_message = f"Error: {e}"
        return error_message, shared


def check(user_input):
    """
    Handle check (correction) mode with the agent, accepting JSON input.
    
    Args:
        user_input (str): The user's input JSON string
        
    Returns:
        tuple: (result, shared) where:
            - result (str): The agent's response or error message
            - shared (dict): The complete shared context dictionary
    """
    # Initialize shared store for this correction turn
    shared = {
        "input_type": "check",
        "user_input": None,
        "response": None
    }
    
    try:
        # Parse input for check mode
        parsed_input = parse_input(user_input, "check")
        shared["user_input"] = parsed_input
        
        # Get the appropriate flow for check mode and run it
        flow = get_flow("check")
        flow.run(shared)
        
        # Get the result
        result = shared["response"]
        
        return result, shared
        
    except ValueError as e:
        error_message = f"Error: {e}\nPlease provide valid JSON input according to the required format."
        return error_message, shared
    except Exception as e:
        error_message = f"Error: {e}"
        return error_message, shared
